'use strict';

const path = require('path');
const fs = require('fs');
const Client = require('ssh2-sftp-client');
const process = require('process')

// 配置
const remoteHost = 'idserver.vip';
const remotePort = 22;
const remoteUsername = 'root';
const remotePassword = '';
const remotePrivateKeyPath = process.env.IDSERVER_SSH_KEY_PATH;
const remotePath = '/usr/share/nginx/html';
const localFolderPath = path.join(__dirname, '..', 'dist');

async function deploy() {
    const conn = new Client();

    let connect_config = {
        host: remoteHost,
        port: remotePort,
        username: remoteUsername,
        password: remotePassword,
        privateKey: fs.readFileSync(remotePrivateKeyPath),
    }
    try {
        await conn.connect(connect_config)
        console.log('连接成功')

        await conn.rmdir(remotePath)
        console.log(`删除 ${remotePath}`)

        await conn.mkdir(remotePath)
        console.log(`创建 ${remotePath}`)

        await conn.uploadDir(localFolderPath, remotePath)
        console.log(`上传 ${remotePath}`)
    } catch(err) {
        console.error(err, 'catch error')
    } finally {
        console.log('end')
        conn.end()
    }
}

deploy()
